package com.heima.wemedia.service.Imp;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WemediaMapper;
import com.heima.wemedia.service.WemediaService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

@Service
public class WemediaServiceImp extends ServiceImpl<WemediaMapper, WmUser> implements WemediaService {
    @Override
    public ResponseResult loginIn(WmUserDTO wmUserDTO)  {
        //1.校验数据
        if (StringUtils.isBlank(wmUserDTO.getName()) || StringUtils.isBlank(wmUserDTO.getPassword())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"数据不能为空");
        }
        //2.查询表中是否存在该用户
        WmUser wmUserInTable = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, wmUserDTO.getName()));
        //对查询的结果进行判断
        if (wmUserInTable == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
        }
        //3.用户存在 进行密码比对
        //将请求中的数据进行加盐加密
        String curPassword = DigestUtils.md5DigestAsHex((wmUserDTO.getPassword() + wmUserInTable.getSalt()).getBytes());
        if (!wmUserInTable.getPassword().equals(curPassword)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误!");
        }
        //4.密码正确 对状态进行判断
        Integer status = wmUserInTable.getStatus();
        if(status != 9){// 可替换为常量
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该用户状态异常，请联系管理员");
        }
        //5.获得token


        //设置map集合封装数据
        HashMap<String, Object> map = new HashMap<>();
        WmUserVO wmUserVO = new WmUserVO();
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUserInTable.getId())));
        try {
            BeanUtils.copyProperties(wmUserVO,wmUserInTable);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        map.put("user",wmUserVO);
        return ResponseResult.okResult(map);
    }
}
